package com.franklin.java.service.database;

import com.franklin.java.api.state.BasePersistentState;
import com.franklin.java.entity.sql.JdbcInfo;
import com.franklin.plugins.common.utils.DataCheckUtils;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.annotations.OptionTag;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author Franklin
 * @since 2021/9/24 14:22
 */
@State(
    name = "com.franklin.java.service.database.JdbcState",
    storages = {@Storage(JdbcState.PERSISTENT_PATH + "JdbcSetting.xml")}
)
public class JdbcState extends BasePersistentState<JdbcState> {

    @OptionTag(converter = JdbcInfoMapConverter.class)
    public Map<String, JdbcInfo> nameJdbcInfoMap = defaultValue();

    public String lastDataSourceName = "";

    public static JdbcState getInstance(){
        return ServiceManager.getService(JdbcState.class);
    }

    public static Map<String, JdbcInfo> getJdbcInfoMap(){
        return getInstance().nameJdbcInfoMap;
    }

    public Map<String, JdbcInfo> defaultValue(){
        return new LinkedHashMap<>();
    }

    public static void addJdbcInfo(String dataSourceName,JdbcInfo jdbcInfo){
        Map<String, JdbcInfo> jdbcInfoMap = getJdbcInfoMap();
        jdbcInfoMap.put(dataSourceName, jdbcInfo);
        getInstance().lastDataSourceName = dataSourceName;
    }

    public static JdbcInfo getLastJdbcInfo(){
        String lastDataSourceName = getInstance().lastDataSourceName;
        Map<String, JdbcInfo> jdbcInfoMap = getJdbcInfoMap();
        if (DataCheckUtils.isNotEmpty(jdbcInfoMap)){
            if (DataCheckUtils.isNotEmpty(lastDataSourceName)){
                JdbcInfo jdbcInfo = jdbcInfoMap.get(lastDataSourceName);
                if (Objects.nonNull(jdbcInfo)) {
                    return jdbcInfo;
                }
            }
            int index = 1;
            int size = jdbcInfoMap.size();
            for (Map.Entry<String, JdbcInfo> entry : jdbcInfoMap.entrySet()) {
                if (index == size){
                    return entry.getValue();
                }
                index++;
            }
        }
        return null;
    }
}
